<template>
  <div class="page-index">
    <div class="page-index__content scroll-box">
      <el-form :model="ruleForm" ref="ruleFormRef" :rules="rules" label-width="150px" :disabled="disabledFlag">
        <div class="content-title">
          <i class="el-icon-document"></i>
          活动基本信息
        </div>
        <div class="content-form">
          <el-form-item label="活动名称" prop="activityName">
            <el-input v-model="ruleForm.activityName" type="text"></el-input>
          </el-form-item>
          <el-form-item label="直播时间" prop="liveStartTime">
            <el-date-picker v-model="ruleForm.liveStartTime" type="datetime" placeholder="选择日期时间" style="width: 100%;"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="活动有效期" prop="activityTime">
            <el-date-picker v-model="ruleForm.activityTime" type="datetimerange" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="兑奖截至时间" prop="cashDeadline">
            <el-date-picker v-model="ruleForm.cashDeadline" type="datetime" placeholder="选择日期时间" style="width: 100%;"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="视频号地址" prop="liveUrl">
            <el-input v-model="ruleForm.liveUrl" type="text" placeholder="请输入视频号地址"></el-input>
          </el-form-item>
          <el-form-item label="活动规则" prop="activityRule">
            <el-input v-model="ruleForm.activityRule" type="textarea" placeholder="请输入活动规则" resize="vertical"
              :autosize="{ minRows: 2 }">
            </el-input>
          </el-form-item>
          <el-form-item label="发布状态" prop="status">
            <el-select v-model="ruleForm.status" :disabled="$route.params.flag" placeholder="请选择发布状态">
              <el-option label="发布" :value="1"></el-option>
              <el-option label="不发布" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </div>

        <div class="content-title">
          <i class="el-icon-document"></i>
          赠品信息
        </div>

        <div class="content-table">
          <el-form-item label-width="0px" prop="promotionActivityPrizeConfigDTOList">
            <el-table :data="tableData" style="width: 100%" border :align="'center'"
              :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
              <el-table-column type="index" label="序号" align="center" width="60" fixed="left"></el-table-column>
              <el-table-column prop="prizeLevelName" label="赠品等级名称" width="130">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.prizeLevelName" :disabled="$route.params.flag"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="giftCode" label="赠品编码"></el-table-column>
              <el-table-column prop="giftName" label="赠品名称"></el-table-column>
              <el-table-column prop="giftPic" label="赠品图片">
                <template slot-scope="scope">
                  <img :src="scope.row.giftPic" v-if="
                    scope.row.giftPic != '' &&
                    scope.row.giftPic != null
                  " width="70" height="50" />
                </template>
              </el-table-column>
              <el-table-column prop="giftDesc" label="赠品描述" show-overflow-tooltip></el-table-column>
              <el-table-column prop="giftType" label="赠品类型">
                <template slot-scope="scope">
                  <span v-if="scope.row.giftType === 1">实物赠品</span>
                  <span v-if="scope.row.giftType === 2">虚拟赠品</span>
                </template>
              </el-table-column>
              <el-table-column prop="deliveryType" label="配送方式" width="240" align="center">
                <template slot-scope="scope">
                  <el-radio-group v-model="scope.row.deliveryType" v-if="scope.row.giftType === 1"
                    :disabled="$route.params.flag" size="mini">
                    <el-radio-button label="1">专卖店配送</el-radio-button>
                    <el-radio-button label="2">五粮液总部配送</el-radio-button>
                  </el-radio-group>
                  <span v-if="scope.row.giftType === 2">——————</span>
                </template>
              </el-table-column>
              <el-table-column prop="prizeQuantity" label="赠品数量" width="100">
                <template slot-scope="scope">
                  <el-input :maxlength="8" oninput="value=value.replace(/[^0-9]/g,'')" v-model="scope.row.prizeQuantity"
                    :disabled="$route.params.flag">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" align="center" width="200px" v-if="!$route.params.flag">
                <template slot-scope="scope">
                  <el-button size="mini" @click="checkjiang(scope.row, scope.$index)" type="text">选择赠品</el-button>
                  <el-button size="mini" @click="delprice(scope.$index)" type="text">删除奖项</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-button type="primary" @click="add()" size="mini" icon="el-icon-edit"
            v-if="!$route.params.flag">增加奖项</el-button>
        </div>
      </el-form>


    </div>

    <div class="page-index__footer">
      <el-button @click="postsure()" type="primary" size="mini" v-if="!$route.params.flag"
        :loading="loading">保存</el-button>
      <el-button @click="delsure()" size="mini">取消</el-button>
    </div>

    <!-- 赠品列表 -->
    <el-dialog title="赠品列表" :visible.sync="dialogVisible" width="80%" @close="closeDialog">
      <div class="gift-form">
        <el-select v-model="giftForm.giftType" placeholder="请选择赠品类型" clearable>
          <el-option label="实物赠品" :value="1"></el-option>
          <el-option label="虚拟赠品" :value="2"></el-option>
        </el-select>
        <el-input v-model="giftForm.giftName" placeholder="请输入赠品名称" style="width: 300px;"></el-input>
        <el-button type="primary" @click="checkjiang()" icon="el-icon-search">查询</el-button>
      </div>
      <el-table :data="giftTableData" style="width: 100%" @select="handleRow" ref="tables"
        @selection-change="handleSelectionChange" border
        :header-cell-style="{ background: '#eef1f6', color: '#606266' }" v-loading="giftLoading" height="400px">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column prop="giftCode" label="赠品编码"></el-table-column>
        <el-table-column prop="giftName" label="赠品名称"></el-table-column>
        <el-table-column prop="giftPic" label="赠品图片">
          <template slot-scope="scope">
            <img :src="scope.row.giftPic" v-if="
              scope.row.giftPic != '' &&
              scope.row.giftPic != null
            " width="70" height="50" />
          </template>
        </el-table-column>
        <el-table-column prop="giftDesc" label="赠品描述"></el-table-column>
        <el-table-column prop="giftType" label="赠品类型">
          <template slot-scope="scope">
            <span v-if="scope.row.giftType === 1">实物赠品</span>
            <span v-if="scope.row.giftType === 2">虚拟赠品</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sure()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { createActivityConfig } from "@/api/lotteryActivityset";
import { qryGiftBank } from "@/api/giftbank";
export default {
  data() {
    return {
      ruleForm: {
        uuid: '',
        activityType: 5,
        activityName: '',
        liveStartTime: '',
        activityTime: [],
        cashDeadline: '',
        liveUrl: '',
        activityRule: '',
        status: 0,
      },
      rules: {
        activityName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        liveStartTime: [
          { required: true, message: '请选择直播时间', trigger: 'blur' },
        ],
        activityTime: [
          { type: 'array', required: true, message: '请选择活动时间', trigger: 'change | blur' },
        ],
        cashDeadline: [
          { required: true, message: '请选择截止时间', trigger: 'blur | change' },
        ],
        liveUrl: [
          { required: true, message: '请输入视频号地址', trigger: 'blur' },
        ],
        activityRule: [
          { required: true, message: '请输入活动规则', trigger: 'blur' },
        ],
      },
      detail: {},
      loading: false,
      disabledFlag: false,
      tableData: [],

      // 选择赠品弹框
      dialogVisible: false,
      giftLoading: false,
      giftTableData: [],
      giftForm: {
        giftType: '',
        giftName: '',
      },
      level: '',
      selectData: [],
      selectGift: [],
    }
  },
  created() {
    if (this.$route.params.edit) {
      const detail = this.detail = this.$route.params.edit;
      this.ruleForm.uuid = detail.uuid;
      this.ruleForm.activityName = detail.activityName;
      this.ruleForm.activityTime = [detail.activityBeginTime, detail.activityEndTime];
      this.ruleForm.liveStartTime = detail.liveStartTime;
      this.ruleForm.cashDeadline = detail.cashDeadline;
      this.ruleForm.liveUrl = detail.liveUrl;
      this.ruleForm.activityRule = detail.activityRule;
      this.ruleForm.status = detail.status;
      this.tableData = this.$route.params.edit.promotionActivityPrizeConfigDTOList;
    }

    if (this.$route.params.flag) {
      this.disabledFlag = true
    }
  },
  methods: {
    checkjiang(v, index) {
      this.level = index
      this.dialogVisible = true;
      const data = {
        size: 99,
        current: 1,
        condition: {
          giftCode: "",
          ActivityType: 5,
          ...this.giftForm
        },
        ascs: [],
        descs: []
      }
      this.giftLoading = true;
      qryGiftBank(data).then(res => {
        res.records.forEach(item => {
          item.validType = item.giftType == 1 ? "2" : "1";
        })
        this.giftTableData = res.records
        if (this.giftTableData.length > 0) {
          for (var i in this.tableData) {
            if (this.tableData[i].giftCode != null && this.tableData[i].giftCode != '' && this.tableData[i].giftCode.length != 0) {
              this.removeByValue(this.giftTableData, "giftCode", this.tableData[i].giftCode);
            }
          }
        }
      }).finally(() => {
        this.giftLoading = false;
      })
    },
    sure() {
      this.dialogVisible = false;
      let tableDataFilter = []
      this.tableData.forEach((item, i) => {
        if (i == this.level) {
          this.selectData[0].prizeLevelName = this.tableData[i].prizeLevelName;
          this.selectData[0].prizeLevel = this.tableData[i].prizeLevel;
          this.selectData[0]["prizeId"] = this.selectData[0]["uuid"];
          delete this.selectData[0]["uuid"];
          let returnedTarget = Object.assign({}, this.tableData[i], this.selectData[0]);
          this.$set(returnedTarget, 'prizeQuantity', 1)
          if (this.selectData[0].giftType == 2) {
            this.$set(returnedTarget, 'deliveryType', '1')
          }
          this.tableData[i] = returnedTarget;
          tableDataFilter = this.tableData;
        }
      })
      this.tableData = [];
      tableDataFilter.forEach(item => {
        this.tableData.push(item)
      })
    },
    handleSelectionChange(val) {
      this.selectData = val;
    },
    // 数组，属性，属性值
    removeByValue: function (arr, attr, value) {
      if (arr == null) {
        return;
      }
      var index = 0;
      for (var i in arr) {
        if (arr[i][attr] == value) {
          index = i;
          break;
        }
      }
      arr.splice(index, 1);
    },
    handleRow(selection, row) {
      // 先清除所有选中的
      this.$refs.tables.clearSelection();
      // 当前的点击实现勾选
      this.$refs.tables.toggleRowSelection(row);
    },
    delprice(index) {
      this.tableData.splice(index, 1);
    },
    add() {
      this.tableData.push({
        prizeLevel: this.tableData.length + 1 + "",
      });
    },
    closeDialog() {
      this.giftForm.giftType = '';
      this.giftForm.giftName = '';
    },
    delsure() {
      this.$router.back();
    },
    postsure() {
      if (this.ruleForm.activityName == "" || this.ruleForm.activityName == null) {
        this.$message.error("请输入活动名称");
        return;
      }
      if (this.ruleForm.activityTime.length <= 0 || this.ruleForm.activityTime == null) {
        this.$message.error("请输入开始日期");
        return;
      }

      if (this.ruleForm.cashDeadline == "" || this.ruleForm.cashDeadline == null) {
        this.$message.error("请选择兑奖截至时间");
        return;
      }

      if (this.ruleForm.liveUrl == "" || this.ruleForm.liveUrl == null) {
        this.$message.error("请输入视频号地址");
        return;
      }

      if (this.ruleForm.activityRule == "" || this.ruleForm.activityRule == null) {
        this.$message.error("请输入活动规则");
        return;
      }

      if (this.tableData.length <= 0) {
        this.$message.error("请添加赠品");
        return;
      }

      for (let i = 0; i < this.tableData.length; i++) {
        if (this.tableData[i].prizeLevelName == "" || this.tableData[i].prizeLevelName == null) {
          this.$message.error("请输入赠品等级名称");
          return;
        }
        if (this.tableData[i].giftCode == "" || this.tableData[i].giftCode == null) {
          this.$message.error("请选择赠品");
          return;
        }
        if (this.tableData[i].prizeQuantity == "" || this.tableData[i].prizeQuantity == null) {
          this.$message.error("请输入赠品数量");
          return;
        }
      }

      this.selectGift = []
      this.tableData.forEach((item, i) => {
        item.prizeLevel = i + 1;
        item.winningRate = 0;
        if (this.tableData[i].giftCode) {
          this.selectGift.push(this.tableData[i])
        }
      })

      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          let data = {
            uuid: this.ruleForm.uuid,
            activityType: 5,
            activityName: this.ruleForm.activityName,
            activityBeginTime: this.ruleForm.activityTime[0],
            activityEndTime: this.ruleForm.activityTime[1],
            liveStartTime: this.ruleForm.liveStartTime,
            cashDeadline: this.ruleForm.cashDeadline,
            liveUrl: this.ruleForm.liveUrl,
            activityRule: this.ruleForm.activityRule,
            status: this.ruleForm.status,
            promotionActivityPrizeConfigDTOList: this.selectGift,
          };

          createActivityConfig(data).then(res => {
            this.giftTableData = res.records
            if (res.code == '1') {
              this.$message({
                showClose: true,
                message: "修改成功",
                type: "success"
              });
              this.$router.back();
            } else {
              this.$message({
                showClose: true,
                message: res.message,
                type: "error"
              });
              this.selectGift = []
            }
          }).finally(() => {
            this.loading = false;
          })
        }
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.content-title {
  margin-bottom: 15px;
  font-size: 20px;
  color: #000;
}

.content-form {
  width: 500px;
}

.add-prize {
  margin-top: 15px;
}

.gift-form {
  display: flex;
  gap: 15px;
  margin-bottom: 15px;
}
</style>